package com.linsen.gateway.config;

import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.hutool.core.util.ArrayUtil;
import com.linsen.core.satoken.constant.SaTokenConstant;
import com.linsen.gateway.handler.SaTokenAuthHandler;
import com.linsen.gateway.handler.SaTokenErrorHandler;
import com.linsen.gateway.props.LinsenGatewayProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhaoyong
 * @date 2023/3/10
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties({LinsenGatewayProperties.class})
public class GatewayConfiguration {
    private final SaTokenAuthHandler saTokenAuthHandler;
    private final SaTokenErrorHandler saTokenErrorHandler;


    @Bean
    // @ConditionalOnProperty(prefix = "linsen.gateway", name = "sa-reactor-filter", havingValue = "true")
    public SaReactorFilter saReactorFilter() {
        log.info("gateway sa-reactor-filter is enabled");
        // 注册 Sa-Token全局过滤器
        return new SaReactorFilter()
                // 拦截地址
                .addInclude("/**")    /* 拦截全部path */
                // 开放地址
                .addExclude(ArrayUtil.toArray(SaTokenConstant.ENDPOINTS, String.class))
                .setAuth(this.saTokenAuthHandler)
                .setError(this.saTokenErrorHandler);
    }
}
